<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, type TableInstance } from 'element-plus'
import { useCartListStore } from '@/stores/modules/cartList'
import type { CartListType } from '@/stores/modules/cartList'
import { useUserStore } from '@/stores/modules/user'
import { getCartListApi } from '@/apis/cart'
import { useRouter } from 'vue-router'

const cartListStore = useCartListStore()
const userStore = useUserStore()
const router = useRouter()

// 获取表格实例
const tableRef = ref<TableInstance>()
// 表格选中数据列表
const multipleSelection = ref<CartListType[]>()
// 购物车数据列表
const cartList = ref<CartListType[]>()
// 获取购物车数据列表
const getCartList = async () => {
  const res = await getCartListApi()
  cartList.value = res.data.result
}
onMounted(async () => {
  // 登录后获取云端购物车列表
  if (userStore.token !== '') {
    getCartList()
  }
  // 未登录获取本地购物车数据
  else {
    cartList.value = cartListStore.cartList
  }

  // 等待DOM更新后设置初始选中状态
  await nextTick()
  setInitialSelection()
})

// 设置初始选中状态
const setInitialSelection = () => {
  cartList.value?.forEach((item) => {
    if (item.selected) {
      tableRef.value?.toggleRowSelection(item, true)
    }
  })
}

// 获取表格选中数据数组
const handleSelectionChange = (val: CartListType[]) => {
  // 同步更新所有商品的selected属性
  // some()检查选中数组中是否存在满足条件的元素
  cartList.value?.forEach((item) => {
    item.selected = val.some((selectedItem) => selectedItem.id === item.id)
  })
  multipleSelection.value = val
}

// 选中商品总价格
const totalPrice = computed(() => {
  return (
    multipleSelection.value
      ?.reduce((total, item) => {
        return total + Number(item.price) * item.count
      }, 0)
      .toFixed(2) || 0
  )
})

// 删除购物车数据
const del = async (skuId: string) => {
  if (userStore.token !== '') {
    cartListStore.deleteCart([skuId])
    getCartList()
  } else {
    cartListStore.deleteLocalCart(skuId)
  }
  ElMessage.success('删除成功')
}

// 去结算
const goSettlement = () => {
  if (userStore.token === '') {
    ElMessage.error('请先登录')
    return
  }

  if (multipleSelection.value === undefined) {
    ElMessage.error('请选择商品再来支付吧！')
    return
  }

  cartListStore.addPayCartList(multipleSelection.value)

  router.push('/checkout')
}
</script>

<template>
  <el-table
    ref="tableRef"
    :data="cartList"
    row-key="id"
    style="width: 1100px; margin: 20px auto; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.18)"
    @selection-change="handleSelectionChange"
    border
  >
    <el-table-column type="selection" width="50"></el-table-column>
    <el-table-column property="picture" label="商品图" width="150" align="center">
      <template #default="scope">
        <img :src="scope.row.picture" alt="" width="100px" height="100px" />
      </template>
    </el-table-column>
    <el-table-column property="name" label="商品名" width="300" align="center" />
    <el-table-column property="price" label="单价" width="100" align="center">
      <template #default="scope">
        <p>￥{{ scope.row.price }}</p>
      </template>
    </el-table-column>
    <el-table-column property="count" label="数量" width="250" align="center">
      <template #default="scope">
        <el-input-number v-model="scope.row.count" :min="1" />
      </template>
    </el-table-column>
    <el-table-column property="address" label="小计" width="100" align="center">
      <template #default="scope">
        <p class="subtotal">￥{{ (scope.row.price * scope.row.count).toFixed(2) }}</p>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="150" align="center">
      <template #default="scope">
        <el-button type="danger" @click="del(scope.row.skuId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="settlement">
    <div class="goodsInfo">
      <p style="text-align: center">
        共 {{ cartList?.length }} 件商品, 已选择 {{ multipleSelection?.length }} 件, 商品合计:
      </p>
      <p class="price">￥{{ totalPrice }}</p>
    </div>
    <el-button @click="goSettlement">去结算</el-button>
  </div>
</template>

<style lang="scss" scoped>
.subtotal {
  font-size: 18px;
  color: red;
}
.settlement {
  width: 1100px;
  height: 60px;
  margin: 10px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid rgba(169, 163, 163, 0.356);
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.18);
  .goodsInfo {
    width: 800px;
    height: 100%;
    line-height: 60px;
    display: flex;
    p {
      width: 260px;
      height: 100%;
      font-size: 15px;
      font-weight: 400;
    }
    .price {
      color: red;
      font-size: 18px;
    }
  }
  .el-button {
    width: 110px;
    height: 40px;
    margin-right: 30px;
    background-color: #45bda3;
    color: white;
  }
}
</style>
